import {Component} from '@angular/core';
import {FormBuilder, Validators, FormGroup} from '@angular/forms'; // form验证
import {ViewController,NavController, AlertController, ToastController} from 'ionic-angular';

import {RegisterPage} from './register/register';
import {UserInfo} from '../../model/userInfo';
import {LoginService} from './loginService';

@Component({
    selector: 'page-login-model',
    templateUrl: 'login.html'
})
export class LoginModelPage {

    userInfo:UserInfo;
    loginForm:FormGroup;
    user_phone:any;
    phone_code:any;

    constructor(
        private viewCtrl:ViewController,
        private alertCtrl:AlertController,
        public navCtrl:NavController,
        private toastCtrl:ToastController,
        private formBuilder:FormBuilder,
        private loginService:LoginService,
    ) {

        this.loginForm = formBuilder.group({
            user_phone: ['18937632575', Validators.compose([Validators.minLength(11), Validators.maxLength(11), Validators.required, Validators.pattern("^(13[0-9]|15[012356789]|17[03678]|18[0-9]|14[57])[0-9]{8}$")])],
            phone_code: ['123456', Validators.compose([Validators.required, Validators.minLength(6)])]
        });
        this.user_phone = this.loginForm.controls['user_phone'];
        this.phone_code = this.loginForm.controls['phone_code'];
    }

    sendCode() {
        let alert = this.alertCtrl.create({
            title: '提示',
            subTitle: '验证码发送成功',
            message: '您的验证码是123456',
            buttons: ['朕知道了']
        });
        alert.present();
    }

    login(value) {
        if (value.phone_code == '123456') {
            this.loginService.login().then(result => {
                if (result['success']) {
                    let data = result['data'];
                    let userInfo = <UserInfo>data;
                    this.userInfo = userInfo;
                    this.viewCtrl.dismiss(userInfo);
                    // this.storage.set('UserInfo', userInfo);
                }
            });
        } else {
            let toast = this.toastCtrl.create({
                message: '验证码这样都能输如错误，你是不是虎',
                duration: 2000,
                position: 'middle'
            });
            toast.present();
        }
    }

    register() {
        this.navCtrl.push(RegisterPage);
    }

    dismiss() {
        this.viewCtrl.dismiss(new UserInfo());
    }
}
